package com.wolf.cx330.view.view

import android.content.Context
import android.graphics.Camera
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.wolf.cx330.base.dp
import com.wolf.cx330.base.getAvatar

/**
 * HenCoderPlus 翻转Demo
 *
 * 3步动画
 * # 1. Camera 旋转30度
 * # 2. Canvas 旋转360度
 * # 另一块
 * # 3. Canvas 旋转-30度
 */
class CameraPlusAnimView(context: Context, attributeSet: AttributeSet) :
    View(context, attributeSet) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val camera = Camera()
    private val imageWidth = 300.dp()
    private val imageHeight = imageWidth
    private val bitmap = resources.getAvatar(imageWidth.toInt())
    private var cameraRotateXB = 0F
        set(value) {
            field = value
            invalidate()
        }
    private var cameraRotateXT = 0F
        set(value) {
            field = value
            invalidate()
        }
    private var canvasRotate = 0F
        set(value) {
            field = value
            invalidate()
        }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //  上方
        canvas.save()
        canvas.translate(width / 2F, height / 2F)
        canvas.rotate(-canvasRotate)
        camera.save()
        camera.rotateX(cameraRotateXT)
        camera.applyToCanvas(canvas)
        camera.restore()
        canvas.clipRect(-imageWidth, -imageHeight, imageWidth, 0F)
        canvas.rotate(canvasRotate)
        canvas.translate(-width / 2F, -height / 2F)
        canvas.drawBitmap(bitmap, width / 2 - imageWidth / 2F, height / 2 - imageHeight / 2F, paint)
        canvas.restore()

        //  下方
        canvas.save()
        //  第一步 将下方抬起
        canvas.translate(width / 2F, height / 2F)
        canvas.rotate(-canvasRotate)
        //  移动回去
        camera.save()
        camera.rotateX(cameraRotateXB)
        camera.applyToCanvas(canvas)
        camera.restore()
        //  camera 变换
        canvas.clipRect(-imageWidth, 0F, imageWidth, imageHeight)
        //  裁切下面
        canvas.rotate(canvasRotate)
        canvas.translate(-width / 2F, -height / 2F)
        //  移动到原点
        canvas.drawBitmap(bitmap, width / 2 - imageWidth / 2F, height / 2 - imageHeight / 2F, paint)
        canvas.restore()
    }
}